
from datetime import datetime
import time
from django.core.paginator import Paginator
from django import http
from django.shortcuts import render
from django.views import View
import json

from django_redis import get_redis_connection

from goods.models import SKU, GoodsCategory, GoodCategoryVisit
from meiduo_mall.utlis.login_required import MyLoginRequiredview
from meiduo_mall.utlis.my_category import get_categories
from meiduo_mall.utlis.response_code import RET
from orders.models import OrderGoods


class SKUListView(View):
    def get(self,request,category_id,page_num):
        # 1,获取分类信息,和过滤参数

        categories = get_categories()#是1.2.3级数据的封装函数

        sort_field=request.GET.get('sort','default')#取sort的值,如果sort没有值返回,比如第一次访问就不会有sort值,默认返回default给前端

        #1.1 判断排序的字段
        if sort_field=='price':
            sort="-price" #按价格降序

        elif sort_field=='hot':
            sort="-sales"  #按销量降序
        else:
            sort='-create_time'#按创建时间排列

        # 2,查询sku数据
        skus = SKU.objects.filter(category_id=category_id).order_by(sort)#按sort排序
        # 3,分页处理
        paginate=Paginator(object_list=skus,per_page=5)#将skus商品列表分为5也
        page=paginate.page(page_num)#获取到前端传来的请求页数
        current_page=page.number#当前页
        skus_list=page.object_list#当前页对象列表
        total_page=paginate.num_pages #总页数



        # 4,获取分类对象
        category = GoodsCategory.objects.get(id=category_id)

        # 拼接数据返回响应
        context = {
            'categories': categories,
            "skus":skus_list,#不在全部返回，而是请求对象页数的列表对象
            'category':category,
            "current_page": current_page,
            "total_page": total_page,
            'sort':sort_field#返回排序响应
        }


        return render(request, 'list.html', context)
#热销排行
class SKUHotListView(View):
    def get(self,request,category_id):
        #1,根据销量查询两条数据
        skus = SKU.objects.filter(category_id=category_id).order_by("-sales")[:3]

        #2,数据转换
        sku_list = []

        for sku in skus:
            sku_list.append({
                "id":sku.id,
                "default_image_url":sku.default_image_url.url,
                "name":sku.name,
                "price":sku.price
            })

        #3,拼接数据,返回响应

        return http.JsonResponse({"hot_sku_list":sku_list})
#详情页展示
class SKUDetailView(View):
    def get(self,request,sku_id):
        #1.获取分类
        categories=get_categories()
        # 2,获取面包屑
        category = SKU.objects.get(id=sku_id).category

        #sku=SKU.objects.get(id=sku_id)
        # category = sku.category


        # 3,获取sku对象
        sku=SKU.objects.get(id=sku_id)
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return http.HttpResponseForbidden("规格不全")
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options
        # 获取评论信息
        # comment_list=OrderGoods.objects.get("comment")
        # 拼接数据,渲染页面

        context={
            "categories":categories,
            "category":category,
            "sku":sku,
            "specs": goods_specs,
        }


        return render(request,'detail.html',context=context)


# 分类访问量类视图(记录当天访问量)
class SKUCategoryVisitCountView(View):
    def post(self,request,category_id):

        #1,取出分类
        category = GoodsCategory.objects.get(id=category_id)

        #2, 查询该分类当天的方法量
        t = time.localtime()#获取本地时间
        current_str = "%d-%02d-%02d"%(t.tm_year,t.tm_mon,t.tm_mday)#拼接当前的时间字符串
        current_date = datetime.strptime(current_str,"%Y-%m-%d")#获取当天日期对象

        try:
            visit_count = category.visit_counts.get(date=current_date)
        except Exception as e:
            visit_count = GoodCategoryVisit()

        #3,重新赋值,入库
        visit_count.count += 1
        visit_count.date = current_date
        visit_count.category_id = category_id
        visit_count.save()

        #4,返回响应
        return http.JsonResponse({"code":RET.OK,"errmsg":"统计成功"})


#保存浏览记录
class UserBrowseHistoryView(MyLoginRequiredview):
    def post(self,request):
        #1,获取参数
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get("sku_id")
        user_id = request.user.id

        #2,校验参数
        if not sku_id:
            return http.JsonResponse({"errmsg":"参数不全"},status=400)

        #3,数据入库
        #3,1 去重,删掉已经存在的sku_id
        redis_conn = get_redis_connection("history")#是刚创建的redis库
        redis_conn.lrem("history_%s"%user_id,0,sku_id)

        #3,2 储存
        redis_conn.lpush("history_%s"%user_id,sku_id)

        #3,3 截取,只保留5个
        redis_conn.ltrim("history_%s"%user_id,0,4)

        #4,返回响应
        return http.JsonResponse({"code":RET.OK,"errmsg":"保存成功"})


    def get(self,requst):

        # 1,获取redis中当前用户所有的历史
        redis_conn=get_redis_connection('history')
        sku_ids=redis_conn.lrange("history_%s"%requst.user.id,0,4)

        ##2,遍历所有商品的编号,取出商品对象
        sku_list=[]
        for sku_id in sku_ids:
            sku=SKU.objects.get(id=sku_id)
            sku_dict={
                "id":sku.id,
                "default_image_url":sku.default_image_url.url,
                "name":sku.name,
                "price": sku.price,
                "sales":sku.sales
            }
            sku_list.append(sku_dict)
          # 3,返回响应
        return http.JsonResponse({"skus": sku_list})


class UserCommentView(MyLoginRequiredview):

    def get(self,request,sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
            order_goods = sku.ordergoods_set.filter(is_commented=True)
        except Exception:
            return http.JsonResponse({"code": RET.NODATA, "errmsg": "获取商品评论信息失败"})
        # 数据入库
        # 返回响应
        count=sku.comments
        comments = list()
        for order_good in order_goods:
            if order_good.is_anonymous == True:
                usermane = "****"
            else:
                usermane = order_good.order.user.username
            comments.append({
                "username": usermane,
                "comment": order_good.comment,
                "score": order_good.score,
                "count":count
            })
        return http.JsonResponse({"code": RET.OK, "goods_comment_list": comments})